package com.systop.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import com.systop.entity.GoodsStock;
import com.systop.entity.Order;
import com.systop.entity.StockLockDetail;
import com.systop.service.GoodsStockService;
import com.systop.service.OrderService;
import com.systop.service.StockLockDetailService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: jsj
 * @Date: 2022/6/17
 */


// @RabbitListener(queues = "stock.release.stock.queue")
@Component
public class HandleOrderCloseRelease implements ChannelAwareMessageListener {

    @Autowired
    StockLockDetailService stockLockDetailService;

    @Autowired
    OrderService orderService;

    @Autowired
    GoodsStockService goodsStockService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        System.out.println("订单关闭，准备解锁库存");
        try {
            // 使用jackson解析
            Order order = JSON.parseObject(new String(message.getBody()), Order.class);
            List<StockLockDetail> orderList = stockLockDetailService.list(new QueryWrapper<StockLockDetail>().eq("order_no", order.getOrderNo()));

            if(orderList!=null && orderList.size()>0){
                //过滤已经回滚的库存信息
                List<StockLockDetail> collect = orderList.stream().filter(orderItem -> {
                    return orderItem.getLockStatus() == 2;
                }).collect(Collectors.toList());
                System.out.println(collect);
                for (StockLockDetail stockLockDetail : collect) {
                    goodsStockService.update(new UpdateWrapper<GoodsStock>()
                            .eq("goods_id", stockLockDetail.getGoodsId())
                            .setSql("lock_stock_num = lock_stock_num - " + stockLockDetail.getGoodsNum()));
                }
                stockLockDetailService.update(new UpdateWrapper<StockLockDetail>()
                        .eq("order_no", order.getOrderNo())
                        .set("lock_status", 2));
            }
            //消费成功后将手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //如果发送失败，消息会重新进入队列，再次被这个消费者消费
            //消息发送失败后，也可以将消息发送到别的队列，让其他消费者进行消费
            //第三个参数 true为重新将消息放入队列，如果设置为false，则抛弃这条消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
